package com.sunny.core.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunny.core.bean.PersonInfo;
import com.sunny.core.bean.PolicyInfo;
import com.sunny.core.bean.PolicyMaster;
import com.sunny.core.bean.UserInfo;
import com.sunny.core.service.IPolicyInfoService;
import com.sunny.core.service.IPolicyMasterService;
import com.sunny.core.utils.CommonResult;
import com.sunny.core.utils.CommonStringUtils;
import com.sunny.core.utils.Constant;

@Controller
@RequestMapping("/policyInfo")
public class PolicyInfoController {

	@Resource(name = "policyMasterService")
	private IPolicyMasterService policyMasterService;

	@Resource(name = "policyInfoService")
	private IPolicyInfoService policyInfoService;

	/**
	 * 保单查询
	 */
	@RequestMapping(value = "/query", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView queryAll(HttpServletRequest request, HttpServletResponse response, Model m) throws Exception {

		PolicyInfo policyInfo = new PolicyInfo();

		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");

		int num = 1;
		int size = 10;
		if (pageNum != null && !"".equals(pageNum)) {
			num = Integer.parseInt(pageNum);
		}
		if (pageSize != null && !"".equals(pageSize)) {
			size = Integer.parseInt(pageSize);
		}
		String sortString = "id.desc";
		Order.formString(sortString);

		PageHelper.startPage(num, size);

		String searchType = request.getParameter("searchType");
		String searchValue = request.getParameter("searchValue");

		if (StringUtils.isNotBlank(searchType)) {
			if (searchType.equals("policyCode")) {
				policyInfo.setPolicyCode(searchValue);
			}
			// if (searchType.equals("2")) {
			// policyInfo.setBirthday(searchValue);
			// }
		}

		List<PolicyInfo> policyInfoList = policyInfoService.query(policyInfo);

		PageInfo<PolicyInfo> pagehelper = new PageInfo<PolicyInfo>(policyInfoList);

		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		// 相当 于request的setAttribut，在jsp页面中通过personList取数据
		// modelAndView.addObject("personList", personList);
		modelAndView.addObject("pagehelper", pagehelper);

		m.addAttribute("policyInfoList", policyInfoList);
		m.addAttribute("total", pagehelper.getTotal());
		m.addAttribute("pageSize", pagehelper.getPageSize());
		m.addAttribute("pageNum", num);
		m.addAttribute("searchType", searchType);
		m.addAttribute("searchValue", searchValue);

		// 指定视图
		// 下边的路径，如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀，修改为
		// modelAndView.setViewName("/jsp/personList.jsp");
		// 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
		modelAndView.setViewName("policy/policy_info_list");
		return modelAndView;

	}

	/**
	 * 读取excel后写入数据库
	 */
	@RequestMapping(value = "/readExcelWriteToDB", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public CommonResult readExcelWriteToDB(HttpServletRequest request, HttpSession session, PersonInfo personInfo)
			throws Exception {

		CommonResult commonResult = new CommonResult();
		commonResult.setStatus(Constant.RESULT_ERROR_CODE);
		commonResult.setMsg(Constant.RESULT_ADDERR_DESC);
		File file = new File("e:/123.xls");
		UserInfo currentUser = (UserInfo) session.getAttribute("currentUser");

		try {
			Workbook wb = Workbook.getWorkbook(file);
			Sheet sheet = wb.getSheet(0);
			int del_flag = 0;
			String create_userid = currentUser.getUserPid();
			String create_username = currentUser.getRealName();
			Date date = new Date();
			PolicyInfo policyInfo = null;
			PolicyMaster policyMaster = null;
			int index = 0;// 表头所在的列，从0列开始数
			Integer mainFlag = 0;
			String policyMasterPid = null;
			boolean flag = false;
			for (int i = 0; i < sheet.getRows(); i++) {
				String num = sheet.getCell(0, i).getContents();
				if ("序号".equals(num)) {
					flag = true;
					continue;
				}
				if (flag) {

					policyInfo = new PolicyInfo();
					String policy_code = sheet.getCell(1, i).getContents();
					String effective_date = sheet.getCell(2, i).getContents();
					String payable_date = sheet.getCell(3, i).getContents();
					String payment_period = sheet.getCell(4, i).getContents();
					String Insurance_period = sheet.getCell(5, i).getContents();
					String holder_name = sheet.getCell(6, i).getContents();
					String insured_name = sheet.getCell(7, i).getContents();
					String postal_address = sheet.getCell(8, i).getContents();
					String holder_phone_num = sheet.getCell(9, i).getContents();
					String holder_home_phone_num = sheet.getCell(10, i).getContents();
					String agent_name = sheet.getCell(11, i).getContents();
					String agent_phone_num = sheet.getCell(12, i).getContents();
					String insurance_name = sheet.getCell(13, i).getContents();

					BigDecimal premium_payable = new BigDecimal(0);

					if (!"-".equals(sheet.getCell(14, i).getContents())) {
						premium_payable = new BigDecimal(Double.valueOf(sheet.getCell(14, i).getContents()));
					}

					String org_code = sheet.getCell(15, i).getContents();
					String payment_method = sheet.getCell(16, i).getContents();
					String oppening_bank = sheet.getCell(17, i).getContents();
					String account_num = sheet.getCell(18, i).getContents();
					String policy_status = sheet.getCell(19, i).getContents();
					String payment_times = sheet.getCell(20, i).getContents();

					policyMasterPid = CommonStringUtils.get32UUID();
					policyInfo.setPolicyInfoPid(CommonStringUtils.get32UUID());
					policyInfo.setPolicyMasterPid(policyMasterPid);
					policyInfo.setPolicyCode(policy_code);
					policyInfo.setEffectiveDate(effective_date);
					policyInfo.setPayableDate(payable_date);
					policyInfo.setPaymentPeriod(payment_period);
					policyInfo.setInsurancePeriod(Insurance_period);
					policyInfo.setHolderName(holder_name);
					policyInfo.setInsuredName(insured_name);
					policyInfo.setPostalAddress(postal_address);
					policyInfo.setHolderPhoneNum(holder_phone_num);
					policyInfo.setHolderHomePhoneNum(holder_home_phone_num);
					policyInfo.setAgentName(agent_name);
					policyInfo.setAgentPhoneNum(agent_phone_num);
					policyInfo.setInsuranceName(insurance_name);
					policyInfo.setPremiumPayable(premium_payable);
					policyInfo.setOrgCode(org_code);
					policyInfo.setPaymentMethod(payment_method);
					policyInfo.setOppeningBank(oppening_bank);
					policyInfo.setAccountNum(account_num);
					policyInfo.setPolicyStatus(policy_status);
					policyInfo.setPaymentTimes(payment_times);
					policyInfo.setDelFlag(del_flag);
					policyInfo.setCreateUserid(create_userid);
					policyInfo.setCreateUsername(create_username);
					policyInfo.setCreateTime(date);

					mainFlag = 0;
					if (insurance_name != null && (insurance_name).indexOf("附加") != -1) {
						mainFlag = 1;// 为附加险
					} else {
						policyMaster = new PolicyMaster();
						policyMaster.setPolicyMasterPid(policyMasterPid);
						policyMaster.setPolicyCode(policy_code);
						policyMaster.setEffectiveDate(effective_date);
						policyMaster.setPayableDate(payable_date);
						policyMaster.setPaymentPeriod(payment_period);
						policyMaster.setInsurancePeriod(Insurance_period);
						policyMaster.setHolderName(holder_name);
						policyMaster.setInsuredName(insured_name);
						policyMaster.setPostalAddress(postal_address);
						policyMaster.setHolderPhoneNum(holder_phone_num);
						policyMaster.setHolderHomePhoneNum(holder_home_phone_num);
						policyMaster.setAgentName(agent_name);
						policyMaster.setAgentPhoneNum(agent_phone_num);
						policyMaster.setInsuranceName(insurance_name);
						policyMaster.setPremiumPayable(premium_payable);
						policyMaster.setOrgCode(org_code);
						policyMaster.setPaymentMethod(payment_method);
						policyMaster.setOppeningBank(oppening_bank);
						policyMaster.setAccountNum(account_num);
						policyMaster.setPolicyStatus(policy_status);
						policyMaster.setPaymentTimes(payment_times);
						policyMaster.setDelFlag(del_flag);
						policyMaster.setCreateUserid(create_userid);
						policyMaster.setCreateUsername(create_username);
						policyMaster.setCreateTime(date);
						policyMasterService.save(policyMaster);
					}
					
					policyInfo.setMainFlag(mainFlag);

					policyInfoService.save(policyInfo);

					commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
					commonResult.setMsg(Constant.RESULT_ADDSUC_DESC);
				}
			}

		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return commonResult;
	}

	@RequestMapping(value = "/delete", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public CommonResult delete(HttpServletRequest request, HttpSession session) throws Exception {
		PolicyInfo policyInfo = new PolicyInfo();
		CommonResult commonResult = new CommonResult();
		String policyInfoPid = request.getParameter("policyInfoPid");
		policyInfo.setPolicyInfoPid(policyInfoPid);
		policyInfo.setDelFlag(1);
		int result = policyInfoService.updateByPrimaryKeySelective(policyInfo);
		if (result == 1) {
			commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
			commonResult.setMsg(Constant.RESULT_DELSUC_DESC);
		} else {
			commonResult.setStatus(Constant.RESULT_ERROR_CODE);
			commonResult.setMsg(Constant.RESULT_DELERR_DESC);
		}
		return commonResult;
	}

	/**
	 * 跳到保单详情页面
	 */
	@RequestMapping(value = "/toDetail", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView toDetail(HttpServletRequest request, HttpServletResponse response, Model m,
			PolicyInfo policyInfo) throws Exception {

		ModelAndView modelAndView = new ModelAndView();

		if (policyInfo != null && StringUtils.isNotBlank(policyInfo.getPolicyInfoPid())) {
			PolicyInfo entity = policyInfoService.selectByPrimaryKey(policyInfo);

			if (entity != null) {

				m.addAttribute("flag", "detail");
				m.addAttribute("policyInfo", entity);

				modelAndView.setViewName("policy/policy_info_crud");
				return modelAndView;
			}
		}
		return null;
	}

	/**
	 * 跳到险种编辑页面
	 */
	@RequestMapping(value = "/toEdit", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView toEdit(HttpServletRequest request, HttpServletResponse response, Model m, PolicyInfo policyInfo)
			throws Exception {

		ModelAndView modelAndView = new ModelAndView();

		if (policyInfo != null && StringUtils.isNotBlank(policyInfo.getPolicyInfoPid())) {
			PolicyInfo entity = policyInfoService.selectByPrimaryKey(policyInfo);

			if (entity != null) {

				m.addAttribute("flag", "edit");
				m.addAttribute("policyInfo", entity);

				modelAndView.setViewName("policy/policy_info_crud");
				return modelAndView;
			}
		}
		return null;
	}

	/**
	 * 跳到保单详细信息新增页面
	 */
	@RequestMapping(value = "/toAdd", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model m,
			PolicyMaster policyMaster) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		
//		String flag = request.getParameter("flag");
		
		session.setAttribute("policyMaster", policyMaster);

		
		modelAndView.setViewName("policy/policy_info_crud");
		return modelAndView;
		
//		if (StringUtils.isNotBlank(policyMaster.getPolicyCode())) {
//			modelAndView.setViewName("policy/policy_info_crud");
//			return modelAndView;
//		} else {
//			
//			return new ModelAndView("redirect:/policyMaster/toAdd.do?flag="+flag);
//		}

	}

	/**
	 * 预添加，将保单主副险信息存入session中
	 */
	@RequestMapping(value = "/preAdd", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView preAdd(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model m,
			PolicyInfo policyInfo) throws Exception {

		String flag =request.getParameter("flag");

		UserInfo currentUser = (UserInfo) session.getAttribute("currentUser");

		PolicyMaster entity = (PolicyMaster) session.getAttribute("policyMaster");

		policyInfo.setPolicyInfoPid(CommonStringUtils.get32UUID());
		policyInfo.setPolicyCode(entity.getPolicyCode());
		policyInfo.setDelFlag(0);
		policyInfo.setCreateTime(new Date());
		policyInfo.setCreateUserid(currentUser.getUserPid());
		policyInfo.setCreateUsername(currentUser.getRealName());

		@SuppressWarnings("unchecked")
		List<PolicyInfo> policyInfoList = (List<PolicyInfo>) session.getAttribute("policyInfoList");

		if (CollectionUtils.isEmpty(policyInfoList)) {
			policyInfoList = new ArrayList<PolicyInfo>();
		}
		policyInfoList.add(policyInfo);

		session.setAttribute("policyInfoList", policyInfoList);

		return new ModelAndView("redirect:/policyMaster/toAdd.do?flag="+flag);

	}
	
	@RequestMapping(value = "/update", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public CommonResult update(HttpServletRequest request,HttpSession session,PolicyInfo policyInfo) throws Exception {	
		CommonResult commonResult = new CommonResult();
		
		commonResult.setStatus(Constant.RESULT_ERROR_CODE);
		commonResult.setMsg(Constant.RESULT_UPERR_DESC);
		
		if (policyInfo != null && policyInfo.getPolicyInfoPid() != null) {
			
			UserInfo currentUser = (UserInfo) session.getAttribute("currentUser");
			policyInfo.setUpdateTime(new Date());
			policyInfo.setUpdateUserid(currentUser.getUserPid());
			policyInfo.setUpdateUsername(currentUser.getRealName());
			
			int result = policyInfoService.updateByPrimaryKeySelective(policyInfo);
			
			if (result == 1) {
				commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
				commonResult.setMsg(Constant.RESULT_UPSUC_DESC);
				commonResult.setData(policyInfo.getPolicyMasterPid());
			}
		}

		return commonResult;
	}	

}
